/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.RecordManagerOptions;
import jdbm.htree.HTree;

/**
 *
 * @author mwh
 */
public class FertilityTableJDBM implements FertilityTable {

    RecordManager recman;

    HTree fertilities;


    public FertilityTableJDBM(FertilityTableMem ftMem, String dbName) throws IOException {

        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);

        // Create idToName hash-fertilities and add TOP as element;
        fertilities = HTree.createInstance(recman);
        recman.setNamedObject("fertilities", fertilities.getRecid());


        for (Iterator<Integer> keyIt = ftMem.keyIterator(); keyIt.hasNext();) {

            Integer key = keyIt.next();
            List<Double> ferts = ftMem.get(key);

            fertilities.put(key, ferts);
            recman.commit();

        }

    }


    public FertilityTableJDBM(String dbName) throws IOException {


        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);
        long recid = recman.getNamedObject("fertilities");
        fertilities = HTree.load(recman, recid);

    }


    public List<Double> get(int word) {
        try {

            return (List<Double>) fertilities.get(word);
        } catch (IOException ex) {
            Logger.getLogger(TranslationTableJDBM.class.getName()).log(Level.SEVERE, null, ex);
        }

        return new ArrayList<Double>();
    }


    public double get(int word, int fert) {
        List<Double> ferts = get(word);

        if (ferts.size() > fert) {
            return ferts.get(fert);
        }
        return Double.NaN;

    }


    public double getLog10(int word, int fert) {
        return Math.log10(get(word, fert));
    }
}


